package com.example.bingobox.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bingobox.R;
import com.example.bingobox.model.Task;
import com.example.bingobox.model.TodoBox;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.ViewHolder> {
    private final List<Task> tasks;
    private final TodoBox todoBox;
    private final TodoBoxAdapter.OnTodoBoxActionListener listener;

    public TaskListAdapter(List<Task> tasks, TodoBox todoBox, 
            TodoBoxAdapter.OnTodoBoxActionListener listener) {
        this.tasks = tasks;
        this.todoBox = todoBox;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_task_in_todobox, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Task task = tasks.get(position);
        holder.nameText.setText(task.getName());
        holder.deadlineText.setText(formatDate(task.getDeadline()));
        
        holder.btnEdit.setOnClickListener(v -> {
            if (listener != null) {
                listener.onEditTask(todoBox, task);
            }
        });
        
        holder.btnDelete.setOnClickListener(v -> {
            if (listener != null) {
                listener.onDeleteTask(todoBox, task);
            }
        });
    }

    @Override
    public int getItemCount() {
        return tasks.size();
    }

    private String formatDate(long timestamp) {
        if (timestamp == 0) {
            return "永久";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView nameText;
        TextView deadlineText;
        View btnEdit;
        View btnDelete;

        ViewHolder(View view) {
            super(view);
            nameText = view.findViewById(R.id.text_task_name);
            deadlineText = view.findViewById(R.id.text_task_deadline);
            btnEdit = view.findViewById(R.id.btn_edit);
            btnDelete = view.findViewById(R.id.btn_delete);
        }
    }
} 